package com.example.speedwaymanager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;

final class HeatAvgsComparator implements Comparator<CRider> {
	@Override
	public int compare(CRider r1, CRider r2) {
		return r1.get_heatResult()._heatAvg.compareTo(r2.get_heatResult()._heatAvg);
	}
}

public class CHeat {

	private ArrayList<CGate> _gates = new ArrayList<CGate>(); // po co to jest?
	private ArrayList<CRider> _riders = new ArrayList<CRider>();
	private Boolean _raceCompleted = false;

	@SuppressWarnings("unchecked")
	public CHeat(ArrayList<CGate> gates) {
		_gates = ((ArrayList<CGate>) gates.clone());
	}

	public CHeat() {
	}

	public void addRiders(ArrayList<CRider> riders) {
		_riders = riders;
	}

	public void run() {
		// simulation
		Iterator<CRider> itRider = _riders.iterator();
		while (itRider.hasNext()) {
			CRider rider = itRider.next();
			rider.get_heatResult()._heatAvg = ((float) (rider.get_avg() + Math
					.random() * rider.get_avg()));
		}
		// set race results
		Collections.sort(_riders, new HeatAvgsComparator());
		assignPoints();
		Collections.reverse(_riders);
		assignBonuses();
		_raceCompleted = true;
	}

	private void assignPoints() {
		for (int i = 0; i < _riders.size(); ++i) {
			_riders.get(i).get_heatResult()._heatPoints = i;
			_riders.get(i).get_matchStats().addHeatPoints(i);
		}
	}

	private void assignBonuses() {
		if (_riders.get(0).get_team().equals(_riders.get(1).get_team())) {
			_riders.get(1).get_matchStats().addHeatBonus();
		} else if (_riders.get(1).get_team().equals(_riders.get(2).get_team())) // TODO
																				// if
																				// exluded
																				// or
																				// defect
																				// there
																				// is
																				// no
																				// bonus
		{
			_riders.get(2).get_matchStats().addHeatBonus();
		}
	}

	public void changeRiders(CRider newRider, CRider oldRider) {
		_riders.remove(oldRider);
		_riders.add(newRider);
	}
	
	public void chageNumbers(CRider newRider, CRider oldRider) {
		
	}
	

	/**
	 * @return the raceCompleted
	 */
	public Boolean get_RaceCompleted() {
		return _raceCompleted;
	}

	/**
	 * @return the _gates
	 */
	public ArrayList<CGate> get_gates() {
		return _gates;
	}

	/**
	 * @return the _riders
	 */
	public ArrayList<CRider> get_riders() {
		return _riders;
	}

	/**
	 * @return the _riders
	 */
	public ArrayList<CRider> get_ridersOfTeam(CTeam team) {
		ArrayList<CRider> riders = new ArrayList<CRider>();
		for (CRider rider : _riders) {
			if (rider.get_team().equals(team.get_name())) {
				riders.add(rider);
			}
		}
		return riders;
	}

	/**
	 * @param _gates the _gates to set
	 */
	public void set_gates(ArrayList<CGate> _gates) {
		this._gates = _gates;
	}
}
